package activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.wq.cycling.DemoApplication;
import com.wq.cycling.R;

import java.io.File;
import java.util.Set;

import bean.MessageForSimple;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.ApiUtil;
import service.AsyncTaskForUpdata;
import util.Constant;
import util.MySharePerference;
import util.dialog.DialogForMenu;
import util.dialog.DialogForUpdata;
import util.dialog.DialogFromMiddle;

/**
 * 主页面activity
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class ParentActivity extends FragmentActivity {

    public DialogForUpdata dialogForUpdata;
    public Intent intent;
    public Bundle bundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DemoApplication.addActivity(this);
        setContentView(R.layout.activity_parent);
        initVersion();
        initView();
        initJpush();
    }
    private void initView(){
        findViewById(R.id.iv_menu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogForMenu dialogForMenu = new DialogForMenu(ParentActivity.this);
                dialogForMenu.setSureListener(new DialogForMenu.Sure() {
                    @Override
                    public void onSure(int mode) {
                        switch (mode){
                            case 1:
                                if(MySharePerference.getShardPerferience(ParentActivity.this,"IMEI","").equals("has")) {
                                    intent = new Intent(ParentActivity.this, SonActivity.class);
                                    bundle = new Bundle();
                                    bundle.putInt("code", Constant.Fortify);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }else{
                                    Toast.makeText(ParentActivity.this,"此功能需要添加GPS设备",Toast.LENGTH_LONG).show();
                                }
                                break;
                            case 2:
                                if(MySharePerference.getShardPerferience(ParentActivity.this,"IMEI","").equals("has")) {
                                    intent = new Intent(ParentActivity.this, SonActivity.class);
                                    bundle = new Bundle();
                                    bundle.putInt("code", Constant.Trace);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }else{
                                    Toast.makeText(ParentActivity.this,"此功能需要添加GPS设备",Toast.LENGTH_LONG).show();
                                }
                                break;
                            case 3:
                                if(MySharePerference.getShardPerferience(ParentActivity.this,"IMEI","").equals("has")) {
                                    intent = new Intent(ParentActivity.this, SonActivity.class);
                                    bundle = new Bundle();
                                    bundle.putInt("code", Constant.Track);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }else{
                                    Toast.makeText(ParentActivity.this,"此功能需要添加GPS设备",Toast.LENGTH_LONG).show();
                                }
                                break;
                            case 4:
                                if(MySharePerference.getShardPerferience(ParentActivity.this,"IMEI","").equals("has")) {
                                    intent = new Intent(ParentActivity.this, SonActivity.class);
                                    bundle = new Bundle();
                                    bundle.putInt("code", Constant.Rall);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }else {
                                    Toast.makeText(ParentActivity.this,"此功能需要添加GPS设备",Toast.LENGTH_LONG).show();
                                }
                                break;
                            case 5:
                                Toast.makeText(ParentActivity.this,"开发中",Toast.LENGTH_LONG).show();
                               /* intent = new Intent(ParentActivity.this, SonActivity.class);
                                bundle = new Bundle();
                                bundle.putInt("code", Constant.ReportLoss_A);
                                intent.putExtras(bundle);
                                startActivity(intent);*/
                                break;
                            case 6:
                                if(MySharePerference.getShardPerferience(ParentActivity.this,"IMEI","").equals("has")) {
                                    intent = new Intent(ParentActivity.this, SonActivity.class);
                                    bundle = new Bundle();
                                    bundle.putInt("code", Constant.SwitchMenu);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }else{
                                    Toast.makeText(ParentActivity.this,"此功能需要添加GPS设备",Toast.LENGTH_LONG).show();
                                }
                                break;
                        }
                    }
                });
                dialogForMenu.show();
            }
        });
    }
    private void  initVersion(){
        ApiUtil.getApiService().getVersion("android","pre").enqueue(new Callback<MessageForSimple>() {
            @Override
            public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
                try {
                    final MessageForSimple entity = response.body();
                    if(entity.getCode().equals("10008")){
                        DialogFromMiddle dialogFormMiddle = new DialogFromMiddle(ParentActivity.this);
                        dialogFormMiddle.setSureListener(new DialogFromMiddle.Sure() {
                            @Override
                            public void onSure() {

                                if(entity.getData().getNativeurl().isEmpty()){
                                    Intent it = new Intent(Intent.ACTION_VIEW);
                                    it.setData(Uri.parse(entity.getData().getWeburl()));
                                    it = Intent.createChooser(it, null);
                                    startActivity(it);
                                }else{
                                    dialogForUpdata = new DialogForUpdata(ParentActivity.this);
                                    dialogForUpdata.show();
                                    AsyncTaskForUpdata task = new AsyncTaskForUpdata(new AsyncTaskForUpdata.Listener() {
                                        @Override
                                        public void finish(String path) {
                                            // TODO Auto-generated method stub
                                            dialogForUpdata.dismiss();
                                            Intent intent2 = new Intent();
                                            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                            intent2.setAction(android.content.Intent.ACTION_VIEW);
                                            Uri uri = Uri.fromFile(new File(path)); // 这里是APK路径
                                            intent2.setDataAndType(uri,"application/vnd.android.package-archive");
                                            startActivity(intent2);
                                        }
                                    },ParentActivity.this);
                                    task.execute(entity.getData().getNativeurl(),"app-axq.apk");
                                    //task.execute("http://openbox.mobilem.360.cn/index/d/sid/3101204","app-zx.apk");
                                }

                            }
                        });
                        if(!entity.getData().getVersion().equals(DemoApplication.getVersion())) {
                            try {
                                int serviceCode = Integer.valueOf(entity.getData().getVersion().replace(".",""));
                                int nowCode = Integer.valueOf(DemoApplication.getVersion().replace(".",""));
                                if(nowCode<serviceCode) {
                                    dialogFormMiddle.show(getResources().getString(R.string.dialog_title4), getResources().getString(R.string.dialog_content4), "", "", getResources().getString(R.string.dialog_yes4), getResources().getString(R.string.dialog_no4), !entity.getData().isForceinstall());
                                }
                            }catch (Exception e){

                            }
                        }
                    }else{
                        Toast.makeText(ParentActivity.this,entity.getMsg(),Toast.LENGTH_LONG).show();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<MessageForSimple> call, Throwable t) {
                Toast.makeText(ParentActivity.this,"服务器发生错误",Toast.LENGTH_LONG).show();
            }
        });
    }

    BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if ("ACTION_UPDATE".equals(intent.getAction())) {
                dialogForUpdata.setProgress(intent.getIntExtra("finished", 0));
            }
        }
    };
    /**
     * 注册极光alias
     */
    private void initJpush(){
        JPushInterface.resumePush(getApplicationContext());
        JPushInterface.setAlias(getApplicationContext(), MySharePerference.getShardPerferience(ParentActivity.this,"ACCOUTN",""), new TagAliasCallback() {

            @Override
            public void gotResult(int arg0, String arg1, Set<String> arg2) {
                // TODO Auto-generated method stub
                Log.d("name", "设置的别名: " + arg1);
            }
        });
    }


    protected void onSaveInstanceState(Bundle outState) {
        // activity被回收的时候不保存fragment避免重复
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_MENU) {// MENU键
            // 监控/拦截菜单键
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            DemoApplication.clearActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("ACTION_UPDATE");
        registerReceiver(broadcastReceiver, intentFilter);
        registerReceiver(mMessageReceiver, new IntentFilter("io.zhixun"));
    }

    // 接收推送过来的广播通知
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Extract mConversationList included in the Intent
            int code = intent.getIntExtra("PushId", 0);
            String content = intent.getStringExtra("Content");
            String title = intent.getStringExtra("Title");
            DialogFromMiddle dialogFormMiddle = new DialogFromMiddle(ParentActivity.this);
            dialogFormMiddle.setSureListener(new DialogFromMiddle.Sure() {
                @Override
                public void onSure() {
                    // TODO Auto-generated method stub
                }
            });
            dialogFormMiddle.show(title, content, "", "", getResources().getString(R.string.dialog_yes2),getResources().getString(R.string.dialog_no2), true);

        }
    };
}
